/**
 * Copyright (c) 2017-2018, Daniel Jiang (thorqq@163.com).
 *
 * Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3 (the "License");
 * 
 * Copyright (C) 2007 Free Software Foundation, Inc. [http://fsf.org/]
 */
package com.thorqq.wuxibusgui;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Group;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import com.thorqq.wuxibusgui.Packet.BusLive;
import com.thorqq.wuxibusgui.Packet.BusLiveStop;
import com.thorqq.wuxibusgui.Packet.LineDirectionInfo;
import com.thorqq.wuxibusgui.Packet.LineDirectionStops;

import org.eclipse.swt.layout.FormAttachment;

/**
 * @author THORQQ
 *
 */
public class WuxibusUnit extends Composite
{
	private Table mTabStops;
	private Combo mComboLine;
	private Label mLblUpdateTime;
	private Label mLblInfo;
	private TableColumn mTblclmnSeq;
	private TableColumn mTblclmnStopname;
	private TableColumn mTblclmnTime;
	private TableColumn mTblclmnBus;
	
	private Thread mQueryThread;

	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public WuxibusUnit(Composite parent, int style)
	{
		super(parent, style);
		setLayout(new FormLayout());
		
		Group group = new Group(this, SWT.NONE);
		group.setLayout(new FormLayout());
		FormData fd_group = new FormData();
		fd_group.right = new FormAttachment(100);
		fd_group.top = new FormAttachment(0);
		fd_group.bottom = new FormAttachment(100);
		fd_group.left = new FormAttachment(0);
		group.setLayoutData(fd_group);
		
		Label label = new Label(group, SWT.NONE);
		label.setText("线路：");
		FormData fd_label = new FormData();
		fd_label.right = new FormAttachment(0, 37);
		fd_label.left = new FormAttachment(0, 10);
		label.setLayoutData(fd_label);
		
		mComboLine = new Combo(group, SWT.NONE);
		FormData fd_combo = new FormData();
		fd_combo.right = new FormAttachment(100, -134);
		fd_combo.left = new FormAttachment(label, 6);
		mComboLine.setLayoutData(fd_combo);
		
		mTabStops = new Table(group, SWT.BORDER | SWT.FULL_SELECTION);
		mTabStops.setLinesVisible(true);
		mTabStops.setHeaderVisible(true);
		FormData fd_table = new FormData();
		fd_table.bottom = new FormAttachment(100, -7);
		fd_table.top = new FormAttachment(0, 60);
		fd_table.right = new FormAttachment(0, 329);
		fd_table.left = new FormAttachment(0, 3);
		mTabStops.setLayoutData(fd_table);
		
		mTblclmnSeq = new TableColumn(mTabStops, SWT.CENTER);
		mTblclmnSeq.setWidth(35);
		mTblclmnSeq.setText("No.");
		
		mTblclmnStopname = new TableColumn(mTabStops, SWT.NONE);
		mTblclmnStopname.setWidth(143);
		mTblclmnStopname.setText("站台名称");
		
		mTblclmnTime = new TableColumn(mTabStops, SWT.CENTER);
		mTblclmnTime.setWidth(65);
		mTblclmnTime.setText("到站");
		
		mTblclmnBus = new TableColumn(mTabStops, SWT.CENTER);
		mTblclmnBus.setWidth(52);
		mTblclmnBus.setText("车号");
		
		mLblUpdateTime = new Label(group, SWT.NONE);
		fd_label.top = new FormAttachment(mLblUpdateTime, 0, SWT.TOP);
		fd_combo.top = new FormAttachment(mLblUpdateTime, -4, SWT.TOP);
		mLblUpdateTime.setText("请选择公交线路");
		mLblUpdateTime.setAlignment(SWT.RIGHT);
		FormData fd_label_1 = new FormData();
		fd_label_1.top = new FormAttachment(0, 6);
		fd_label_1.right = new FormAttachment(100, -13);
		fd_label_1.left = new FormAttachment(mComboLine, 6);
		mLblUpdateTime.setLayoutData(fd_label_1);
		
		mLblInfo = new Label(group, SWT.NONE);
		mLblInfo.setText("线路信息");
		FormData fd_label_2 = new FormData();
		fd_label_2.top = new FormAttachment(mComboLine, 10);
		fd_label_2.left = new FormAttachment(0, 10);
		fd_label_2.right = new FormAttachment(100, -6);
		mLblInfo.setLayoutData(fd_label_2);

		setListener();
	}

	@Override
	protected void checkSubclass()
	{
		// Disable the check that prevents subclassing of SWT components
	}
	
	public void setAllLines(List<String> lines)
	{
		for(String l : lines)
		{
			mComboLine.add(l);
		}
	}
	
	protected void setListener()
	{
		//界面销毁时停止后台线程
		this.addDisposeListener(new DisposeListener(){

			@Override
			public void widgetDisposed(DisposeEvent event)
			{
				stop();
			}
			
		});
		
		//输入回车，开始监控
		mComboLine.addKeyListener(new KeyListener()
		{

			@Override
			public void keyPressed(KeyEvent event)
			{
				if(event.keyCode == SWT.CR)
				{
					mComboLine.setListVisible(false);
				}
				else
				{
					mComboLine.setListVisible(true);
				}
			}

			@Override
			public void keyReleased(KeyEvent event)
			{
				
			}
	
		});
		
		//选中某条线路
		mComboLine.addSelectionListener(new SelectionListener(){

			@Override
			public void widgetDefaultSelected(SelectionEvent event)
			{
				
			}

			@Override
			public void widgetSelected(SelectionEvent event)
			{
				try
				{
					mComboLine.setListVisible(false);
					mTabStops.removeAll();

					String line = mComboLine.getText();
					monitorLine(line);
				}
				catch (Exception e)
				{
					Log.ex(e);
					e.printStackTrace();
				}
			}
		});
	}
	
	protected void monitorLine(String line) throws Exception
	{

		//获取线路id
		final List<LineDirectionInfo> lineInfo = BusUtils.searchLineInfo(line);
		if(lineInfo.size() == 0)
		{
			return;
		}
		
		//获取站台信息
		int preSeq = -1;
		List<LineDirectionStops> lineStops = BusUtils.getLineStops(lineInfo.get(0).line_id);
		for(LineDirectionStops ds : lineStops)
		{
			for(Packet.StopInfo s : ds.stops)
			{
				if(s.stop_seq == preSeq)
				{
					continue;
				}
				else
				{
					preSeq = s.stop_seq;
				}
				
				TableItem row = new TableItem(mTabStops, SWT.None, s.stop_seq - 1);
				if(s.stop_type_id == 12)
				{
                    row.setText(new String[]{
                            "" + s.stop_seq, 
                            s.stop_type_name + " " + s.stop_name,
                            ""
                            });
                    row.setBackground(new Color(Display.getCurrent(), 255, 255, 176));
				}
				else
				{
                    row.setText(new String[]{
                            "" + s.stop_seq, 
                            " " + s.stop_name,
                            ""
                            });
				}
			}
		}
		
		//移到表格的最上面
		mTabStops.setSelection(0);
		mTabStops.deselectAll();

		//获取到站信息
		stop();
		
		mQueryThread = new Thread(new Runnable(){

			@Override
			public void run()
			{
				//mRun = true;
				
				while(true)
				{
					try
					{
						//有些线路有多个code，例如10路，分为正转和反转两个方向
						Set<String> lineCodeList = new HashSet<String>();
						for(int i = 0; i < lineInfo.size(); i++)
						{
							lineCodeList.add(lineInfo.get(i).line_code);
						}
						
						String info = "";
						List<BusLiveStop> busLiveStop = new ArrayList<BusLiveStop>();
						for(String code : lineCodeList)
						{
							BusLive busLive = BusUtils.getBusLive(code);
							busLiveStop.addAll(busLive.list);			
							if("".equals(info))
							{
								info = busLive.info;
							}
						}
						
						updateArrival(info, busLiveStop);
						
						int cnt = 50;
						while(--cnt > 0)
						{
							Thread.sleep(100);
						}
					}
					catch (Exception e)
					{
						//e.printStackTrace();
						return;
					}
				}
				
			}
			
		});
		mQueryThread.start();

	}
	
	public void stop()
	{
		//mRun = false;
		if(mQueryThread != null)
		{
			mQueryThread.interrupt();
			mQueryThread = null;
		}
	}
	
	public void setDefaltLine(String line)
	{
		try
		{
			mComboLine.setText(line);
			monitorLine(line);
		}
		catch (Exception e)
		{
			Log.ex(e);
			e.printStackTrace();
		}
	}
	
	//更新到站信息
	protected void updateArrival(final String info, final List<BusLiveStop> busLiveStop)
	{
		Display.getDefault().asyncExec(new Runnable() {
            @Override
            public void run() {
                //对控件的操作代码
            	SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            	String timeNow = sdf.format(new Date());
            	mLblUpdateTime.setText("最近更新：" + timeNow);
            	
            	mLblInfo.setText(info);
            	
    			for(TableItem item : mTabStops.getItems())
    			{
					item.setText(2, "");
					item.setText(3, "");
    			}
    			
        		for(BusLiveStop arrival : busLiveStop)
        		{
        			int seq = arrival.stop_seq;
        			
        			for(TableItem item : mTabStops.getItems())
        			{
        				if(Integer.parseInt(item.getText(0).trim()) == seq)
        				{
        					item.setText(2, "" + arrival.actdatetime);
        					item.setText(3, "" + arrival.busselfid);        					
        				}
        			}
        		}

            }
        });
		

	}

}
